<template>
  <div class="department-container">
    <div class="app-container">
      <el-card>
        <!-- 用一个行列布局 -->
        <el-row type="flex" justify="space-between" align="middle" style="height: 40px">
          <el-col :span="20">
            <svg-icon icon-class="gongzi" /><span>江苏传智播客教育科技股份有限公司</span>
          </el-col>
          <el-col :span="4">
            <el-row type="flex" justify="end">
              <!-- 两个内容 -->
              <el-col>负责人</el-col>
              <!-- 下拉菜单 element -->
              <el-col>
                <el-dropdown>
                  <span>
                    操作<i class="el-icon-arrow-down" />
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item @click.native="hShowAdd('')">添加子部门</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
        <el-tree :data="list" default-expand-all>
          <template v-slot="{data}">
            <el-row type="flex" justify="space-between" align="middle" style="height: 40px; width: 100%">
              <el-col :span="20">
                <svg-icon icon-class="tree" /><span>{{ data.name }}</span>
              </el-col>
              <el-col :span="4">
                <el-row type="flex" justify="end">
                  <!-- 两个内容 -->
                  <el-col>{{ data.manager }}</el-col>
                  <!-- 下拉菜单 element -->
                  <el-col>
                    <el-dropdown>
                      <span>
                        操作<i class="el-icon-arrow-down" />
                      </span>
                      <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item @click.native="hShowAdd(data.id)">添加子部门</el-dropdown-item>
                        <el-dropdown-item @click.native="hShowEdit(data.id)">编辑部门</el-dropdown-item>
                        <el-dropdown-item v-if="data.children.length === 0" @click.native="hDel(data.id)">删除部门</el-dropdown-item>
                      </el-dropdown-menu>
                    </el-dropdown>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-tree>
      </el-card>
    </div>
    <!-- dialog提示框 -->
    <el-dialog
      title="添加"
      :visible.sync="showVisible"
      width="50%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <addor-edit v-if="showVisible" :id="cureId" :new-list="newList" :is-edit="idEdit" @success="hSuccess" @close="hClose" />
    </el-dialog>
    <el-dialog
      title="编辑"
      :visible.sync="showVisibleEdit"
      width="50%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <addor-edit v-if="showVisibleEdit" :id="cureId" :new-list="newList" :is-edit="idEdit" @success="hSuccess" @close="hClose" />
    </el-dialog>

    <!--  当封装相同组件时，很容易碰到数据残留 bug，主要原因是dialog 隐藏没有销毁组件，导致数据残留
    解决方案：
    1. 使用v-if人为的让组件的销毁与创建，（最推荐，无bug 影虎体验好，性能略弱）
    2. 随着dialog的显示与隐藏，手动调用子组件犯法。重新加载数据。 使用$refs和$nexttick()配合一起使用 （不怎么推荐）
    3. 在子组件中监听id的变化，然后直接调用渲染数据 （不推荐使用）
     -->
  </div>
</template>

<script>
import { delDepartmentsEdit, getDepartments } from '@/api/departments'
import { tranListToTreeData } from '@/utils'
import addorEdit from './deptDialog.vue'
export default {
  components: { addorEdit },
  data() {
    return {
      // 依赖一份树形数据
      // 依赖一份树形数据
      // list: [{
      //   name: '财务部',
      //   manager: '刘备',
      //   children: [
      //     {
      //       name: '财务核算部',
      //       manager: '张飞'
      //     },
      //     {
      //       name: '税务核算部',
      //       manager: '关羽'
      //     }
      //   ]
      // }]
      list: [], // 获取部门信息
      showVisible: false, // dialog 关闭
      cureId: '', // ,点击获取的id
      idEdit: false,
      showVisibleEdit: false,
      newList: []
    }
  },
  created() {
    this.loadDepartments()
  },
  methods: {
    // 根据id删除部门
    async  hDel(id) {
      // this.$confirm('确定要删除吗？', '提示', {
      //   type: 'warning'
      // })
      //   .then(async() => {
      //     try {
      //       // 发送请求
      //       const res = await delDepartmentsEdit(id)
      //       this.$message.success(res.message)
      //       this.loadDepartments()
      //     } catch (error) {
      //       this.$message.error(error.message)
      //     }
      //   })
      // 解决嵌套问题
      const result = await this.$confirm('确定要删除吗？', '提示', { type: 'warning' }).catch(e => e)

      if (result !== 'confirm') return
      // 发送请求
      // 判断页面条数
      if (this.list.length === 1 && this.q.page > 1) this.q.page--
      const res = await delDepartmentsEdit(id)
      this.$message.success(res.message)
      this.loadDepartments()
    },
    // 点击编辑
    hShowEdit(id) {
      this.idEdit = true
      this.cureId = id
      this.showVisibleEdit = true
    },
    // 获取用户部门数据
    async  loadDepartments() {
      const res = await getDepartments()
      res.data.depts.shift()
      // 筛选数组
      this.newList = res.data.depts.map(({ id, pid, name, code }) => ({ id, pid, name, code }))
      // console.log(this.newList)
      this.list = tranListToTreeData(res.data.depts)
    },
    // 点击添加
    hShowAdd(id) {
      this.idEdit = false

      // 打开dialog
      this.showVisible = true
      // 传参到子组件
      this.cureId = id
    },
    // 关闭dialog 重新获取
    hSuccess() {
      // 关闭dialog
      this.showVisible = false
      this.showVisibleEdit = false
      // 重新获取数据渲染列表
      this.loadDepartments()
    },
    // 点击取消关闭dialog
    hClose() {
      // 关闭dialog
      this.showVisible = false
      this.showVisibleEdit = false
    }
  }
}
</script>
